﻿
Imports std
Imports storoomc

Public Module raranker

    Public Const defaultConfigfile As String = "raranker.ini"
    Public WithEvents tcpserver As tcpServer2 = Nothing

    Public Sub unhandledException(ByVal e As Exception)
        finishmain()
    End Sub

    Public Sub startservice()
        tcpserver = New tcpServer2()
        tcpserver.port = config.port
    End Sub

    Public Sub shutdown()
        If Not tcpserver Is Nothing Then
            tcpserver.stop()
        End If
    End Sub

    Public Sub monitor()
        While Not consoleCancelKeyPressed() _
            AndAlso ((Not tcpserver Is Nothing AndAlso tcpserver.active()) OrElse config.refreshing())
            sleep()
        End While
    End Sub

    Public Sub main(ByVal args() As String)
        startmain(AddressOf unhandledException)

        Dim configfile As String = Nothing
        configfile = defaultConfigfile
        If args.Length() > 0 Then
            configfile = args(0)
        End If
        If Not config.open(configfile) Then
            raiseError("cannot open configfile " + configfile, errorHandle.errorType.exclamation)
            GoTo ext
        End If

        startservice()
        monitor()
ext:
        finishmain()
    End Sub

    Private Sub tcpserver_receive(ByVal handle As tcpServer2.talkHandle) Handles tcpserver.receive
        handlers.handle(handle)
    End Sub
End Module
